<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--资产类别列表数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="assetName"
            placeholder="请输入资产类别名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="categoryOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--资产类别信息数据-->
      <el-col :span="20" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['asset:category:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['asset:category:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['asset:category:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['asset:category:import']"
            >导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['asset:category:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="类别id" align="center" key="assetId" prop="assetId" v-if="columns[0].visible" width="100"/>
          <el-table-column label="类别编码" align="center" key="assetCode" prop="assetCode" v-if="columns[1].visible" :show-overflow-tooltip="true" width="100"/>
          <el-table-column label="类别名称" align="center" key="assetName" prop="assetName" v-if="columns[2].visible" :show-overflow-tooltip="true" width="150"/>
          <el-table-column label="资产类型" align="center" key="assetType" v-if="columns[3].visible" :show-overflow-tooltip="true" width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.a_asset_type" :value="scope.row.assetType"/>
            </template>
          </el-table-column>


          <el-table-column label="权限部门" align="center" key="deptName" prop="dept.deptName" v-if="columns[3].visible" :show-overflow-tooltip="true" width="100" />
          <el-table-column label="采购计划是否需要总经理审批" align="center" key="planIsAdminApprove" prop="planIsAdminApprove" v-if="columns[5].visible" :show-overflow-tooltip="true" width="250" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.a_is_admin_approve" :value="scope.row.planIsAdminApprove"/>
            </template>
          </el-table-column>
          <el-table-column label="资产调拨是否需要总经理审批" align="center" key="allotIsAdminApprove" prop="allotIsAdminApprove" v-if="columns[6].visible" :show-overflow-tooltip="true" width="250">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.a_is_admin_approve" :value="scope.row.allotIsAdminApprove"/>
            </template>
          </el-table-column>

          <el-table-column label="资产外借是否需要总经理审批" align="center" key="lendoutIsAdminApprove" prop="lendoutIsAdminApprove" v-if="columns[7].visible" :show-overflow-tooltip="true" width="250">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.a_is_admin_approve" :value="scope.row.lendoutIsAdminApprove"/>
            </template>
          </el-table-column>
          <el-table-column label="资产维修是否需要总经理审批" align="center" key="maintenanceIsAdminApprove" prop="maintenanceIsAdminApprove" v-if="columns[8].visible" :show-overflow-tooltip="true" width="250">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.a_is_admin_approve" :value="scope.row.maintenanceIsAdminApprove"/>
            </template>
          </el-table-column>
          <el-table-column label="资产报废是否需要总经理审批" align="center" key="retirementIsAdminApprove" prop="retirementIsAdminApprove" v-if="columns[9].visible" :show-overflow-tooltip="true" width="250">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.a_is_admin_approve" :value="scope.row.retirementIsAdminApprove"/>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" key="remark" prop="remark" v-if="columns[10].visible" :show-overflow-tooltip="true" />
          <el-table-column label="创建人" align="center" key="createName" prop="createName" v-if="columns[11].visible" :show-overflow-tooltip="true" />
          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[12].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['asset:category:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="handleAdd(scope.row)"
                v-hasPermi="['asset:category:add']"
                :style="{ display: scope.row.assetType=='S'?'none':'' }"
              >新增</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['asset:category:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改资产类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" label-position="top">
        <el-row>
          <el-col :span="24">
            <el-form-item label="资产类型" prop="assetType">
              <el-radio-group v-model="form.assetType" :disabled="assetTypeDisabled" @change="assetTypeChange">
                <el-radio label="B">大类</el-radio>
                <el-radio label="C">中类</el-radio>
                <el-radio label="S">小类</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.assetType != 'B'">
            <el-form-item label="上级类别" prop="parentId">
              <el-select v-model="form.parentId" filterable  placeholder="请选择上级类别" >
                <el-option
                  v-for="item in superiorAssetList"
                  :key="item.assetId"
                  :label="item.assetName"
                  :value="item.assetId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="资产名称" prop="assetName">
              <el-input v-model="form.assetName" placeholder="请输入资产名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="form.assetType == 'S'">
            <el-form-item prop="planIsAdminApprove">
              <span slot="label">
                <el-tooltip content="选择“是”发起采购计划OA审批时，如果选择该资产类型则需要总经理审批" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
               采购计划是否需要总经理审批
              </span>
              <el-radio-group v-model="form.planIsAdminApprove">
                <el-radio
                  v-for="dict in dict.type.a_is_admin_approve"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.assetType == 'S'">
            <el-form-item prop="allotIsAdminApprove">
              <span slot="label">
                <el-tooltip content="选择“是”发起资产调拨OA审批时，如果选择该资产类型则需要总经理审批" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                资产调拨是否需要总经理审批
              </span>
              <el-radio-group v-model="form.allotIsAdminApprove">
                <el-radio
                  v-for="dict in dict.type.a_is_admin_approve"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.assetType == 'S'">
            <el-form-item prop="lendoutIsAdminApprove">
              <span slot="label">
                <el-tooltip content="选择“是”发起资产外借OA审批时，如果选择该资产类型则需要总经理审批" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
               资产外借是否需要总经理审批
              </span>
              <el-radio-group v-model="form.lendoutIsAdminApprove">
                <el-radio
                  v-for="dict in dict.type.a_is_admin_approve"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="form.assetType == 'S'">
            <el-form-item prop="maintenanceIsAdminApprove">
              <span slot="label">
                <el-tooltip content="选择“是”发起资产维修OA审批时，如果选择该资产类型则需要总经理审批" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                资产维修是否需要总经理审批
              </span>
              <el-radio-group v-model="form.maintenanceIsAdminApprove">
                <el-radio
                  v-for="dict in dict.type.a_is_admin_approve"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.assetType == 'S'">
            <el-form-item prop="retirementIsAdminApprove">
              <span slot="label" >
                <el-tooltip content="选择“是”发起资产报废OA审批时，如果选择该资产类型则需要总经理审批" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                资产报废是否需要总经理审批
              </span>
              <el-radio-group v-model="form.retirementIsAdminApprove">
                <el-radio
                  v-for="dict in dict.type.a_is_admin_approve"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="form.assetType == 'S'">
            <el-form-item label="归属部门" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"
                        :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 资产类别信息导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的类别数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  addCategory,
  categoryTreeSelect,
  delCategory, deptTreeSelect,
  getCategory,
  getSuperiorByAssetType,
  listCategory,
  updateCategory
} from '@/api/asset/category'
import { getToken } from '@/utils/auth'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import IconSelect from '@/components/IconSelect/index.vue'
import { sourceMap } from '@vue/cli-service/lib/config/terserOptions'

export default {
  name: "Category",
  dicts: ['a_asset_type','a_is_admin_approve'],
  components: { IconSelect, Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资产类信息表格数据
      categoryList: null,
      // 弹出层标题
      title: "",
      // 资产类别树选项
      categoryOptions: undefined,
      // 部门树选项
      deptOptions: undefined,
      //新增时上级资产类别列表
      superiorAssetList: undefined,
      // 是否显示弹出层
      open: false,
      // 资产类别名称
      assetName: undefined,
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 资产类别信息导入参数
      upload: {
        // 是否显示弹出层（资产类别导入）
        open: false,
        // 弹出层标题（资产类别导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/asset/category/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: 0
      },
      // 列信息
      columns: [
        { key: 0, label: `资产类别id`, visible: false },
        { key: 1, label: `资产类别编码`, visible: true },
        { key: 2, label: `资产类别名称`, visible: true },
        { key: 3, label: `资产类型`, visible: true },
        { key: 4, label: `权限部门`, visible: true },
        { key: 5, label: `采购计划是否需要总经理审批`, visible: true },
        { key: 6, label: `资产调拨是否需要总经理审批`, visible: true },
        { key: 7, label: `资产外借是否需要总经理审批`, visible: true },
        { key: 8, label: `资产维修是否需要总经理审批`, visible: true },
        { key: 9, label: `资产报废是否需要总经理审批`, visible: true },
        { key: 10, label: `备注`, visible: true },
        { key: 11, label: `创建人`, visible: true },
        { key: 12, label: `创建时间`, visible: true }
      ],
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级类别不能为空", trigger: "blur" },
        ],
        assetName: [
          { required: true, message: "资产类别名称不能为空", trigger: "blur" },
          { min: 2, max: 10, message: '用户名称长度必须介于 2 和 10 之间', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: "权限部门不能为空", trigger: "blur" },
        ],
        planIsAdminApprove: [
          { required: true, message: "采购计划是否需要总经理审批不能为空", trigger: "blur" },
        ],
        allotIsAdminApprove: [
          { required: true, message: "资产调拨是否需要总经理审批不能为空", trigger: "blur" },
        ],
        lendoutIsAdminApprove: [
          { required: true, message: "资产外借是否需要总经理审批不能为空", trigger: "blur" },
        ],
        maintenanceIsAdminApprove: [
          { required: true, message: "资产维修是否需要总经理审批不能为空", trigger: "blur" },
        ],
        retirementIsAdminApprove: [
          { required: true, message: "资产报废是否需要总经理审批不能为空", trigger: "blur" },
        ]
      },
      assetTypeDisabled:false
    };
  },
  watch: {
    // 根据名称筛选部门树
    assetName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getCategoryTree();
  },
  methods: {
    /** 查询资产类型列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询资产类型下拉树结构 */
    getCategoryTree() {
      categoryTreeSelect().then(response => {
        this.categoryOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.parentId = data.id;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        assetId: undefined,
        parentId: 0,
        assetName: undefined,
        assetType: "B",
        deptId: undefined,
        planIsAdminApprove: undefined,
        allotIsAdminApprove: undefined,
        lendoutIsAdminApprove: undefined,
        maintenanceIsAdminApprove: undefined,
        retirementIsAdminApprove: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.parentId = undefined;
      this.queryParams.assetType = 'B';
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.assetId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.open = true;
      this.title = "添加资产类别";
      this.assetTypeDisabled = false;
      if(row.assetType ==='B'){
        this.assetTypeChange('C');
        this.form.assetType='C';
        this.form.parentId=undefined;
        this.assetTypeDisabled=true;
      }
      if(row.assetType ==='C'){
        this.form.assetType='S';
        this.assetTypeChange('S');
        this.form.parentId=undefined;
        this.form.planIsAdminApprove ='0';
        this.form.allotIsAdminApprove ='0';
        this.form.lendoutIsAdminApprove ='0';
        this.form.maintenanceIsAdminApprove ='0';
        this.form.retirementIsAdminApprove ='0';
        this.assetTypeDisabled=true;
      }

    },
    /** 新增时变更资产类别 */
    assetTypeChange(value) {
      if(value !=='B'){
        this.form.parentId=undefined;
      }
      if(value === 'S'){
        this.form.planIsAdminApprove ='0';
        this.form.allotIsAdminApprove ='0';
        this.form.lendoutIsAdminApprove ='0';
        this.form.maintenanceIsAdminApprove ='0';
        this.form.retirementIsAdminApprove ='0';
      }
      getSuperiorByAssetType(value).then(response => {
        this.superiorAssetList = [];
        this.superiorAssetList = response.data;
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const assetId = row.assetId || this.ids;
      getCategory(assetId).then(response => {
        this.form = response.data;
        getSuperiorByAssetType(response.data.assetType).then(response => {
          this.superiorAssetList = [];
          this.superiorAssetList = response.data;
        });
        this.open = true;
        this.title = "修改资产类别";
        this.assetTypeDisabled=true
      });

    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.assetId != undefined) {
            updateCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.getDeptTree();
              this.getCategoryTree();
              this.reset();
            });
          } else {
            console.log(this.form.parentId)
            addCategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.getDeptTree();
              this.getCategoryTree();
              this.reset();
            });
          }
        }

      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const assetIds = row.assetId || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + assetIds + '"的数据项？').then(function() {
        return delCategory(assetIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('asset/category/export', {
        ...this.queryParams
      }, `资产类别信息模板-${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "资产类别信息导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('asset/category/importTemplate', {
      }, `资产类别模板-${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
      this.getDeptTree();
      this.getCategoryTree();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
